﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;

#if UNITY_EDITOR
public class AssetExport
{
    const string EXPORT_PATH = "/export";

    [MenuItem("导出资源/导出所选资源")]
    static void ExportScene()
    {
        string savePath = EditorUtility.SaveFilePanel("Save Resource", "", "New Resource", "assetbundle");
        if (savePath == string.Empty)
            return;

        string fileName = Path.GetFileName(savePath);
        Object[] sels = Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.Assets);
        List<string> paths = new List<string>();
        for (int i = 0; i < sels.Length; i++)
        {
            var obj = sels[i];
            var path = AssetDatabase.GetAssetPath(obj);
            if (path != null)
            {
                paths.Add(path);
            }
        }
        AssetBundleBuild[] build = new AssetBundleBuild[1];
        build[0].assetNames = paths.ToArray();
        build[0].assetBundleName = fileName;

        string export = GetRootPath(EXPORT_PATH);
        if (!Directory.Exists(export))
            Directory.CreateDirectory(export);
        BuildPipeline.BuildAssetBundles(export, build, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows64);

        string temp = export + "/" + fileName;
        var data = File.ReadAllBytes(temp);
        File.WriteAllBytes(savePath, data);
        File.Delete(temp);
    }

    static string GetRootPath(string relativePath)
    {
        return Application.dataPath + relativePath;
    }
}
#endif 
